package com.ss.project.xia17user.core.aspect;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 请求地址打印器
 * @author xia17
 */
@Slf4j
public class VisitInterceptor implements HandlerInterceptor {


    /**
     *
     * @param request 请求
     * @param response 返回
     * @param handler /
     * @return /
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler){
        String uri = request.getRequestURI();
        log.info("[URI]: {" + uri + "}");
        log.info("[getMethod]: {" + request.getMethod() + "}");
        log.info("[getQueryString]: {" + request.getQueryString() + "}");
        //从request中获取http请求的url/请求的方法类型／响应该http请求的类方法／IP地址／请求中的参数
        log.info("-----------------------------------------------------------------------------------------------------------");
        //ip
        log.info("访问IP[IP] = {" + request.getRemoteAddr() + "}");
        //url
        log.info("请求地址[URL] = {" + request.getRequestURI() + "}");
        //method
        log.info("HTTP方法[method] = {" + request.getMethod() + "}");
        //控制层
        Map<String, String[]> map = request.getParameterMap();
        map.forEach((a, b) -> log.info(a + "  : " + join(b)));
        log.info("-----------------------------------------------------------------------------------------------------------");
        return true;
    }

    /**
     * 拼接参数
     * @param strings 参数
     * @return /
     */
    private String join(String[] strings){
        if (strings == null){
            return "";
        }
        if (strings.length == 0){
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < strings.length; i++) {
            sb.append(strings[i]);
            if (i != strings.length -1){
                sb.append(",");
            }
        }
        return sb.toString();
    }

}
